import React, { Component } from 'react';
import {AtIcon, AtInput, AtButton} from 'taro-ui'
import Taro from '@tarojs/taro';
import {Block, Image, Text, View} from '@tarojs/components'
import {
  COUPON_POSTER,
  EXCHANGE_DETAIL,
  INTERGRAL_EXCHAGE
} from "../../constants/api";
import {user} from "../../utils/user.service";
import {newHttp} from "../../utils/request";
import {GetRequest, vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './detail.scss'

export default class ExchangeCode extends Component {
  state: {
    uuid: string
    shareImg: string
    listInfo: object | false
    showLoading: boolean
    show: boolean
    imgSrc: string
    type: 0 | 1
    exchangeCode: string
    exchangeCodeShow: boolean
    exchangeInfo: any
  } = {
    uuid: '',
    shareImg: '',
    listInfo: false,
    showLoading: true,
    show: false,
    imgSrc: '',
    type: 0,
    exchangeCode: '',
    exchangeCodeShow: false,
    exchangeInfo: []
  }

  async UNSAFE_componentWillMount() {
  }

  async componentDidShow() {
    vcmonitor(this)
    const {showLoading} = this.state
    if (showLoading) {
      const uuid = Taro.getCurrentInstance().router.params.uuid || 0
      const listInfo = await this.getData(uuid)
      this.setState({listInfo})
    }
  }

  async getData(uuid) {
    const listInfo = await newHttp.catchGet(EXCHANGE_DETAIL, {uuid})
    return listInfo || false
  }

  async saveImg() {
    const setting = await Taro.getSetting()
    const {shareImg} = this.state
    if (!setting.authSetting['scope.writePhotosAlbum']) {
      const r = await Taro.authorize({
        scope: 'scope.writePhotosAlbum',
      }).catch(() => {
        Taro.showModal({
          title: '提示',
          content: '我们需要权限帮您保存海报到相册，请打开保存到相册',
          cancelText: '不需要',
          confirmText: '好的',
          success: (ret) => {
            if (ret.confirm) {
              Taro.openSetting()
            }
          }
        })
      })
      return false
    }
    Taro.showLoading({title: '下载中...'})
    Taro.getImageInfo({
      src: shareImg,
    }).then((res) => {
      Taro.hideLoading()
      Taro.saveImageToPhotosAlbum({
        filePath: res.path,
      }).then(() => {
        Taro.showToast({
          title: '保存成功，请进入相册查看',
          icon: 'none'
        })
      })
    }).catch(err => {
      console.log(err)
      Taro.hideLoading()
      Taro.showToast({title: '海报不存在', icon: 'none'})
    })
    this.closeWow()
  }

  async closeWow() {
    const {show, listInfo} = this.state
    Taro.showLoading({title: '加载中...'})
    const shareImg = await newHttp.catchPost(COUPON_POSTER + listInfo.DT_RowId, {})
    Taro.hideLoading()
    this.setState({
      shareImg,
      show: !show
    })
  }

  async receive(integral_id, e) {
    e.stopPropagation()
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const {listInfo, exchangeCode} = this.state
    const that = this
    that.state.exchangeCodeShow = true
    const ret = await newHttp.post(INTERGRAL_EXCHAGE, {integral_id, code: exchangeCode}, true)
    if (ret.data) {
      listInfo.is_can_receive = ret.data.data
      Taro.showToast({
        title: '兑换成功',
        icon: 'none',
        mask: true
      })
      that.setState({listInfo})
      setTimeout(() => {
        that.setState({listInfo}, () => {
          let mpkey = ''
          const uInfo = Taro.getStorageSync('user') || ''
          if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
            mpkey = uInfo.mpkey
          }
          Taro.redirectTo({url: '/main/my/integral/integral' + '?mpkey=' + mpkey})
        })
      }, 1500)
    } else {
      Taro.showToast({
        title: ret.message || '领取失败',
        icon: 'none',
        mask: true
      })
      that.setState({exchangeInfo: ret}, () => {
      })
    }
  }

  goUse(listInfo, e) {
    e.stopPropagation()
    const url = listInfo.url || '/main/coupon/coupon-goods?id=' + listInfo.id
    Taro.navigateTo({
      url
    })
  }

  handleChange(value) {
    this.setState({
      exchangeCode: value
    })
    // 在小程序中，如果想改变 value 的值，需要 `return value` 从而改变输入框的当前值
    return value
  }

  render() {
    const {show, shareImg, listInfo, type, exchangeCodeShow, exchangeInfo} = this.state
    return (
      <View className='coupon-detail-root exchange-code-root'>
        <GzhAuth />
        {listInfo && <Block>
          {show && <View className='coupon-wow'>
            <View className='coupon-wow-bj' onClick={this.closeWow.bind(this)} />
            <Image className='coupon-wow-img' src={shareImg} />
            <View className='coupon-wow-save' onClick={this.saveImg.bind(this)}>保存到相册</View>
          </View>}
          <View className='top-info'>
            <View className='top-info-mj'>{listInfo.name}</View>
            <View className='top-info-e'><Text>{listInfo.integral}</Text><View
              className='jifen'
            >{process.env.integralName}</View></View>
            <View className='top-info-xz'>{listInfo.state}</View>
            {!!type && !!listInfo.isCanToUse &&
            <View className='top-info-lq' onClick={this.goUse.bind(this, listInfo)}>去使用</View>}
            <View className='top-info-lq' onClick={() => {
              this.setState({exchangeCodeShow: true})
            }}
            >立即兑换</View>
            {listInfo.is_can_receive === 2 && <Image className='top-info-lq-p'
              src='https://resource.ivcheng.com/upload/images/20210525/1621945212040_603.png'
            />}
            {!!listInfo.share_type && <View className='top-info-share' onClick={this.closeWow.bind(this)}>
              <AtIcon prefixClass='xxhz' value='fenxiang' size='28' color='#fff' />
            </View>}
          </View>
          <View className='more-info'>
            <View className='more-info-item'>
              <View className='more-info-title'>兑换有效期</View>
              <View className='more-info-desc'>{listInfo.valid_date_start} - {listInfo.valid_date_end}</View>
            </View>
            <View className='more-info-item'>
              <View className='more-info-title'>使用规则</View>
              <View className='more-info-desc'>{listInfo.rule}</View>
            </View>
            <View className='more-info-item'>
              <View className='more-info-title'>使用说明</View>
              <View className='more-info-desc'>
                <text>{listInfo.explain || '每人每兑换码限领一次'}</text>
              </View>
            </View>
          </View>
        </Block>}
        {exchangeCodeShow && <View className='curtainRoot'>
          <View className='exchangeCode-root'>
            <View className='title'>兑换码</View>
            <View className='tips' />
            <View className='item item-one'>
              <AtInput
                name='exchangeCode'
                type='number'
                placeholder='请填写你的兑换码'
                value={this.state.exchangeCode}
                onChange={this.handleChange.bind(this)}
              />
            </View>
            {!!exchangeInfo.message ?
              <View className='tips'>请确认您的兑换码是否正确或未使用过</View>
              :
              <View className='tips' />
            }
            <View className='item'>
              <AtButton onClick={this.receive.bind(this, listInfo.integral_id)}>确定兑换</AtButton>
            </View>
            <View onClick={() => {
              this.setState({exchangeCodeShow: false})
            }} className='close'
            ><AtIcon prefixClass='car' value='iconguanbi' color='#D8D8D8' />
            </View>
          </View>
        </View>}
      </View>
    )
  }
}
